package com.cloudcross.ssp.web.advertiser.main.ad;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.model.Order;
import com.cloudcross.ssp.service.IAccountService;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IOrderService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/advertiser/main/ad/order")
public class OrderController extends SimpleController {

    @Autowired
    private IOrderService               orderService;

    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;

    @Autowired
    private ILogService                 logService;

    @Autowired
    private IAdvertiserService          advertiserService;

    @Autowired
    private IAccountService             accountService;

    /**
     * @return 返回到订单管理第一页。
     */
    @RequestMapping
    public String index(Model model, @RequestParam Long advertiserId) {
        model.addAttribute("advertiserId", advertiserId);
        return redirect(page("list"));
    }

    @RequestMapping("/list")
    public String list(Model model, @RequestParam HashMap<String, Object> paramMap,
                       @RequestParam(defaultValue = "2") Integer status, @RequestParam(defaultValue = "1") int page) {
        Account account = getLoginUser();
        paramMap.put("agentId", account.getAgentId());
        //下拉框选择。默认传进来有advertiserId。 若是选择全部，advertiserId=-1 ，此时标记adMark = “全部”；
        //在mapper里面需要判断
        if (paramMap.get("advertiserId") != null && !"".equals(paramMap.get("advertiserId"))
                && !"-1".equals(paramMap.get("advertiserId"))) {
            paramMap.put("advMark", null);
            model.addAttribute("advertiserId", paramMap.get("advertiserId"));
            String advertiserName = advertiserService.selectAdvertiserNameById(Long.valueOf(paramMap
                    .get("advertiserId").toString()));
            model.addAttribute("selectedadvertiserName", advertiserName);
        } else {
            paramMap.put("advertiserId", -1l);
            paramMap.put("selectedadvertiserName", "全部广告主");
            paramMap.put("advMark", "全部");
        }
        //状态判断
        if (status != 2) {
            paramMap.put("status", new Integer(status));
        } else {
            paramMap.put("status", null);
        }
        // 查询总行数
        int totalRow = orderService.countByParams(paramMap);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);

        List<Order> orderList = orderService.findByParams(paramMap, pager);
        if (status == 2) {
            paramMap.put("status", new Long(2));
        }
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("orderList", orderList);
        return page("list");
    }

    /**
     * 订单修改记录
     * 
     * @param model
     * @param orderId
     * @param page
     * @return
     */
    @RequestMapping("/update")
    public String update(Model model, @RequestParam Long orderId, @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();//存放查询条件
        condition.put("tableName", "t_order");
        condition.put("recordId", orderId);
        int totalRow = logService.findLogCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<Log> logList = logService.findLogByCondition(condition, pager);
        Order order = orderService.findById(orderId);
        model.addAttribute("pager", pager);
        model.addAttribute("logList", logList);
        model.addAttribute("orderId", orderId);
        model.addAttribute("advertiserId", order.getAdvertiserId());
        return page("update");
    }

    /**
     * @return 创建订单。
     */
    @RequestMapping("/create")
    public String create(Model model,@RequestParam Long advertiserId) {
        model.addAttribute("advertiserId", advertiserId);
        Account account = getLoginUser();
        model.addAttribute("agentId", account.getAgentId());
        //获取account List
        List<Account> accountList = accountService.findByParamsAdvertiser(advertiserId);
        model.addAttribute("accountList", accountList);
        //只有内部账户才能出现利润率字段
        if (account.getAdvertiserId().intValue() == 1) {
        	model.addAttribute("test", "true");
        } else {
        	model.addAttribute("test", "false");
        }
        return page("create");
    }

    /**
     * 单个或者批量启用功能。
     * 
     * @return 成功则返回"ok"
     */
    @RequestMapping("enable")
    public @ResponseBody String enable(Long[] id, HttpServletRequest request) {
        Date date  = new Date();
        if (ArrayUtils.isNotEmpty(id)) {
            //循环得到订单名称（批量或者单个都可以）__为了插入log记录的时候显示订单名称！
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < id.length; i++) {
                Order order = orderService.findById(new Long(id[i]));
                list.add(order.getName());
            }
            if (orderService.updateStatus(LangUtil.array2List(id), Status.enable.value)) {
                orderService.updateSupdatedAll(LangUtil.array2List(id), date);
                //如果开启订单成功，向log数据库中插入记录！
                String action;
                for (int i = 0; i < id.length; i++) {
                    action = "开启了订单：" + list.get(i);
                    logService.saveLogAction(request, "Order", "t_order", id[i], action,"enable");
                }
            }
        }
        return OK;
    }

    /**
     * 单个或者批量禁用功能。
     * 
     * @return 成功则返回"ok"
     */
    @RequestMapping("disable")
    public @ResponseBody String disable(Long[] id, HttpServletRequest request) {
        Date date = null;
        if (ArrayUtils.isNotEmpty(id)) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < id.length; i++) {
                Order order = orderService.findById(new Long(id[i]));
                list.add(order.getName());
            }
            date = new Date();
            if (orderService.updateStatus(LangUtil.array2List(id), Status.disable.value)) {
                orderService.updateSupdatedAll(LangUtil.array2List(id), date);
                //如果禁用订单成功，向log数据库中插入记录！
                String action;
                for (int i = 0; i < id.length; i++) {
                    action = "停用了订单：" + list.get(i);
                    logService.saveLogAction(request, "Order", "t_order", id[i], action,"disable");
                }
            }
        }
        return OK;
    }

    /**
     * @return 保存订单，返回到订单管理。
     */
    @RequestMapping("/save")
    public String save(Model model, @ModelAttribute("form") Order order, HttpServletRequest request) {
        model.addAttribute("advertiserId", order.getAdvertiserId());
        order.setAgentId(getLoginUser().getAgentId());
        Account account = getLoginUser();
        if (order.getProfit() == null) {
            order.setProfit(0);
        }
        order.setDateStart(order.getDateStart());
        order.setDateEnd(order.getDateEnd());
        String action;
        if (order.getId() == null) {
            order.setStatus(0);
            if (account.getOperatorId() != 0) {
                order.setOperatorId(account.getOperatorId());
            } else {
                order.setOperatorId(new Long(0));
            }
            if (orderService.add(order)) {
                long newId = orderService.findByName(order.getName());
                action = "新增订单：" + newId;
                logService.saveLogAction(request, "Order", "t_order", newId, action,"add");
            }
        } else {
            Order formerOrder = orderService.findById(order.getId());
            if (orderService.edit(order)) {
                String msg = order.getName() + "：";
                if (!formerOrder.getName().equals(order.getName())) {
                    msg = msg.concat("订单名称  " + formerOrder.getName() + " > " + order.getName() + " / ");
                }
                if (formerOrder.getBudget() != (order.getBudget())) {
                    msg = msg.concat("总预算  " + formerOrder.getBudget() + " > " + order.getBudget() + " / ");
                }
                if (!formerOrder.getOwnerId().equals(order.getOwnerId())) {
                    msg = msg.concat("订单所属人 " + formerOrder.getOwnerId() + " > " + order.getOwnerId());
                }
                logService.saveLogAction(request, "Order", "t_order",order.getId(), msg,"modify");
            }
        }
        return redirect(page("list"));
    }

    /**
     * @return 编辑订单
     */
    @RequestMapping("/edit")
    public String edit(Model model,@RequestParam Long advertiserId,@RequestParam Long orderId) {
        Order order = orderService.findById(orderId);
        model.addAttribute("order", order);
        String activeTime = order.getDateStart() + " to " + order.getDateEnd();
        //获取account List
        List<Account> accountList = accountService.findByParamsAdvertiser(advertiserId);
        model.addAttribute("accountList", accountList);
        model.addAttribute("dateRangePicker", activeTime);
        Account account = getLoginUser();
        //只有内部账户才能出现利润率字段
        if (account.getAdvertiserId().intValue() == 1) {
        	model.addAttribute("test", "true");
        } else {
        	model.addAttribute("test", "false");
        }
        return page("edit");
    }

    /**
     * @return 删除订单将其状态改为-1。
     */
    @RequestMapping("delete")
    public @ResponseBody String delete(Long[] id, HttpServletRequest request) {
        if (ArrayUtils.isNotEmpty(id)) {
            //循环得到订单名称（批量或者单个都可以）_________为了插入log记录的时候显示订单名称！_________
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < id.length; i++) {
                Order order = orderService.findById(new Long(id[i]));
                list.add(order.getName());
            }
            if (orderService.updateStatusAll(LangUtil.array2List(id), Status.delete.value)) {
                for (int i = 0; i < id.length; i++) {
                    String action = "删除了订单:" + list.get(i);
                    logService.saveLogAction(request, "Order", "t_order",id[i], action,"delete");
                }
            }
        }
        return OK;
    }

    /**
     * 获取状态
     * 
     * @param status
     * @return
     */
    private String getStatusStr(int status) {
        if (status == 0) {
            return "正常";
        } else if (status == 1) {
            return "停用";
        } else if (status == 2) {
            return "全部";
        } else {
            return "";
        }
    }

    /**
     * 订单信息导出excel
     * 
     * @param response
     * @param advertiserId
     * @param status
     * @param searchValue
     */
    @RequestMapping("/exportDataReportExcel")
    public void exportDataReportExcel(HttpServletResponse response, Long advertiserId,
                                      @RequestParam(defaultValue = "2") int status, String searchValue) {
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("advertiserId", advertiserId);
        String advertiserName = advertiserService.selectAdvertiserNameById(advertiserId);
        condition.put("advertiserName", advertiserName);

        //按状态搜索
        if (status != 2) {
            condition.put("status", status);
            condition.put("statusName", getStatusStr(status));
        } else {
            condition.put("statusName", "全部");
        }
        //搜索框
        if (StringUtils.isNotBlank(searchValue)) {
            try {
                searchValue = new String(searchValue.trim().getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            condition.put("searchValueStr", searchValue.trim());
            condition.put("value", "%" + searchValue.trim() + "%");

        }
        /**
         * 参数和list里要一样
         */
        List<Order> reportList = orderService.findDeliverEffectAnalysis(condition);
        condition.put("dataList", reportList);
        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "orderReport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列和行的总数进行指定
        int column = 9;
        condition.put("dataSize", (reportList.size() + 100));
        condition.put("column", column);

        String excelOrder = templateProcessor.processTemplate("excel/orderReport.ftl", condition);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelOrder);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 订单修改记录导出
     * 
     * @param response
     * @param orderId
     */
    @RequestMapping("/exportLogExcel")
    public void exportLogExcel(HttpServletResponse response, @RequestParam Long orderId) {
        Map<String, Object> condition = new HashMap<String, Object>();//存放查询条件
        condition.put("tableName", "t_order");
        condition.put("recordId", orderId);
        List<Log> reportList = logService.findLogByCondition(condition, null);
        condition.put("dataList", reportList);
        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "orderModify" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列和行的总数进行指定
        int column = 6;
        condition.put("dataSize", (reportList.size() + 100));
        condition.put("column", column);
        String name = this.orderService.selectOrderNameById(orderId);
        condition.put("message", "订单" + name + "修改记录");
        String excelOrder = templateProcessor.processTemplate("excel/logReport.ftl", condition);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelOrder);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
